package cn.com.shadowless.xinning.utils;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.AsyncQueryHandler;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.core.app.NotificationCompat;

import java.util.ArrayList;
import java.util.List;

import cn.com.shadowless.xinning.R;
import me.leolin.shortcutbadger.ShortcutBadger;

/**
 * The type Badge utils.
 *
 * @author sHadowLess
 */
public class BadgeUtils {

    private static final String TAG = BadgeUtils.class.getSimpleName();

    /**
     * The constant BRAND_XI_AO_MI.
     */
    public static final String BRAND_XI_AO_MI = "Xiaomi";

    /**
     * The constant BRAND_HUA_WEI.
     */
    public static final String BRAND_HUA_WEI = "Huawei";
    /**
     * The constant BRAND_OP_PO.
     */
    public static final String BRAND_OP_PO = "OPPO";
    /**
     * The constant BRAND_VI_VO.
     */
    public static final String BRAND_VI_VO = "vivo";

    private static final int VI_VO_FLAG = 0x01000000;
    /**
     * The constant BRAND_SAM_SUNG.
     */
    public static final String BRAND_SAM_SUNG = "samsung";

    /**
     * The constant BRAND_LEN_OVO.
     */
    public static final String BRAND_LEN_OVO = "Lenovo";

    /**
     * The constant BRAND_HTC.
     */
    public static final String BRAND_HTC = "HTC";
    /**
     * The constant BRAND_SONY.
     */
    public static final String BRAND_SONY = "sony";
    /**
     * The constant BRAND_HONOR.
     */
    public static final String BRAND_HONOR = "honor";

    private static String getLauncherClassName(Context context) {
        ComponentName launchComponent = getLauncherComponentName(context);
        if (launchComponent == null) {
            return "";
        } else {
            return launchComponent.getClassName();
        }
    }

    private static ComponentName getLauncherComponentName(Context context) {
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context
                .getPackageName());
        if (launchIntent != null) {
            return launchIntent.getComponent();
        } else {
            return null;
        }
    }

    /**
     * Sets badge add.
     *
     * @param badgeNum the badge num
     * @param context  the context
     */
    public static void setBadge(int badgeNum, Context context) {
        switch (Build.BRAND) {
            case BRAND_XI_AO_MI:
                setXiaoMiBadge(badgeNum, context);
                break;
            case BRAND_HONOR:
            case BRAND_HUA_WEI:
                setHuaWeiHonorBadge(badgeNum, context);
                break;
            case BRAND_OP_PO:
                if (!setOPPOBadge1(badgeNum, context)) {
                    setOPPOBadge2(badgeNum, context);
                }
                break;
            case BRAND_VI_VO:
                setVivoBadge(badgeNum, context);
                break;
            case BRAND_SAM_SUNG:
                setSamsungBadge(badgeNum, context);
                break;
            case BRAND_LEN_OVO:
                setLenovoBadge(badgeNum, context);
                break;
            case BRAND_HTC:
                setHTCBadge(badgeNum, context);
                break;
            case BRAND_SONY:
                setSonyBadge(badgeNum, context);
                break;
            default:
                ShortcutBadger.applyCount(context, badgeNum);
                break;
        }
    }

    /**
     * Sets xiao mi badge.
     *
     * @param count   the count
     * @param context the context
     */
    public static void setXiaoMiBadge(int count, Context context) {
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(context, TAG)
                .setContentTitle("")
                .setContentText("")
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setAutoCancel(true)
                .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
                .build();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 8.0之后添加角标需要NotificationChannel
            NotificationChannel channel = new NotificationChannel(TAG, TAG, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setShowBadge(true);
            mNotificationManager.createNotificationChannel(channel);
        }
        ShortcutBadger.applyNotification(context, notification, count);
        mNotificationManager.notify(count, notification);
        mNotificationManager.cancelAll();
    }

    /**
     * Sets hua wei honor badge.
     *
     * @param count   the count
     * @param context the context
     */
    public static void setHuaWeiHonorBadge(int count, Context context) {
        try {
            Bundle bunlde = new Bundle();
            bunlde.putString("package", context.getPackageName());
            bunlde.putString("class", context.getPackageName() + ".view.activity.SplashActivity");
            bunlde.putInt("badgenumber", count);
            context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, bunlde);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Sets vivo badge.
     *
     * @param count   the count
     * @param context the context
     */
    @SuppressLint("WrongConstant")
    public static void setVivoBadge(int count, Context context) {
        try {
            String launcherClassName = getLauncherClassName(context);
            if (!TextUtils.isEmpty(launcherClassName)) {
                Intent intent = new Intent("some_action");
                intent.setAction("launcher.action.CHANGE_APPLICATION_NOTIFICATION_NUM");
                intent.putExtra("packageName", context.getPackageName());
                intent.putExtra("className", launcherClassName);
                intent.putExtra("notificationNum", count);
                intent.addFlags(VI_VO_FLAG);
                context.sendBroadcast(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Sets samsung badge.
     *
     * @param count   the count
     * @param context the context
     */
    public static void setSamsungBadge(int count, Context context) {
        try {
            String launcherClassName = getLauncherClassName(context);
            if (!TextUtils.isEmpty(launcherClassName)) {
                Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
                intent.putExtra("badge_count", count);
                intent.putExtra("badge_count_package_name", context.getPackageName());
                intent.putExtra("badge_count_class_name", launcherClassName);
                context.sendBroadcast(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Sets lenovo badge.
     *
     * @param count   the count
     * @param context the context
     */
    public static void setLenovoBadge(int count, Context context) {
        try {
            Bundle extra = new Bundle();
            ArrayList<String> ids = new ArrayList<>();
            extra.putStringArrayList("app_shortcut_custom_id", ids);
            extra.putInt("app_badge_count", count);
            Uri contentUri = Uri.parse("content://com.android.badge/badge");
            context.getContentResolver().call(contentUri, "setAppBadgeCount", null, extra);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Sets htc badge.
     *
     * @param count   the count
     * @param context the context
     */
    public static void setHTCBadge(int count, Context context) {
        try {
            ComponentName launcherComponentName = getLauncherComponentName(context);
            if (launcherComponentName != null) {
                Intent intent1 = new Intent("com.htc.launcher.action.SET_NOTIFICATION");
                intent1.putExtra("com.htc.launcher.extra.COMPONENT", launcherComponentName.flattenToShortString());
                intent1.putExtra("com.htc.launcher.extra.COUNT", count);
                context.sendBroadcast(intent1);
                Intent intent2 = new Intent("com.htc.launcher.action.UPDATE_SHORTCUT");
                intent2.putExtra("packagename", launcherComponentName.getPackageName());
                intent2.putExtra("count", count);
                context.sendBroadcast(intent2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean setOPPOBadge1(int count, Context context) {
        try {
            Bundle extras = new Bundle();
            extras.putInt("app_badge_count", count);
            context.getContentResolver().call(Uri.parse("content://com.android.badge/badge"),
                    "setAppBadgeCount", String.valueOf(count), extras);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean setOPPOBadge2(int count, Context context) {
        try {
            Intent intent = new Intent("com.oppo.unsettledevent");
            intent.putExtra("packageName", context.getPackageName());
            intent.putExtra("number", count);
            intent.putExtra("upgradeNumber", count);
            PackageManager packageManager = context.getPackageManager();
            List<ResolveInfo> receivers = packageManager.queryBroadcastReceivers(intent, 0);
            if (receivers.size() > 0) {
                context.sendBroadcast(intent);
            } else {
                Bundle extras = new Bundle();
                extras.putInt("app_badge_count", count);
                context.getContentResolver().call(Uri.parse("content://com.android.badge/badge"),
                        "setAppBadgeCount", null, extras);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean setSonyBadge(int count, Context context) {
        String launcherClassName = getLauncherClassName(context);
        if (TextUtils.isEmpty(launcherClassName)) {
            return false;
        }
        try {
            //官方给出方法
            ContentValues contentValues = new ContentValues();
            contentValues.put("badge_count", count);
            contentValues.put("package_name", context.getPackageName());
            contentValues.put("activity_name", launcherClassName);
            SonyAsyncQueryHandler asyncQueryHandler = new SonyAsyncQueryHandler(context.getContentResolver());
            asyncQueryHandler.startInsert(0, null, Uri.parse("content://com.sonymobile.home" + ".resourceprovider/badge"), contentValues);
            return true;
        } catch (Exception e) {
            try {
                //网上大部分使用方法
                Intent intent = new Intent("com.sonyericsson.home.action.UPDATE_BADGE");
                intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", count > 0);
                intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME",
                        launcherClassName);
                intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String
                        .valueOf(count));
                intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context
                        .getPackageName());
                context.sendBroadcast(intent);
                return true;
            } catch (Exception e1) {
                e1.printStackTrace();
                return false;
            }
        }
    }

    /**
     * The type Sony async query handler.
     */
    static class SonyAsyncQueryHandler extends AsyncQueryHandler {
        /**
         * Instantiates a new Sony async query handler.
         *
         * @param cr the cr
         */
        SonyAsyncQueryHandler(ContentResolver cr) {
            super(cr);
        }
    }
}
